package interviewpreparationkit.array

/**
 * [Array Manipulation](https://www.hackerrank.com/challenges/crush)
 */
// Complete the arrayManipulation function below.
fun arrayManipulation(n: Int, queries: Array<Array<Int>>): Long {
    // arr[i] + arr[i+1] + ... + arr[n-1] 作为最终数组上第i个元素的值
    val arr = Array(n) { _ -> 0L }

    for (query in queries) {  // a, b, k
        val a = query[0]
        val b = query[1]
        val k = query[2].toLong()
        // [a, n] 区间内的元素都加上 k
        arr[a - 1] = arr[a - 1] + k
        if (b < n) {
            // [b, n] 都减去 k
            arr[b] -= k
        }
    }
    var t = 0L
    var max = 0L
    for (i in 0 until n) {
        t += arr[i]
        if (t > max) max = t
    }
    return max
}